package model

import (
	"context"
	"gin_vue_blog/utils"
	"gin_vue_blog/utils/errmsg"
	"github.com/qiniu/go-sdk/v7/auth/qbox"
	"github.com/qiniu/go-sdk/v7/storage"
	"mime/multipart"
)

var server = utils.Config_Message.QiniuyunServer

func UploadFile(file multipart.File, fileSize int64) (string, int) {
	putPolicy := storage.PutPolicy{
		Scope: server.Bucket,
	}

	// 获取上传token
	mac := qbox.NewMac(server.AccessKey, server.SecretKey)
	upToken := putPolicy.UploadToken(mac)

	// 设置上传配置
	cfg := setConfig()

	// 构建表单上传的对象
	formUploader := storage.NewFormUploader(cfg)
	ret := storage.PutRet{}

	putExtra := storage.PutExtra{}
	err := formUploader.PutWithoutKey(context.Background(), &ret, upToken, file, fileSize, &putExtra)
	if err != nil {
		return "", errmsg.ERROR
	}
	url := server.Domain + ret.Key
	return url, errmsg.SUCCESS
}

func setConfig() *storage.Config {
	return &storage.Config{
		Region:        selectZone(server.Zone),
		UseHTTPS:      false,
		UseCdnDomains: false,
	}
}

func selectZone(Zone int) *storage.Zone {
	switch server.Zone {
	case 1:
		return &storage.ZoneHuadong
	case 2:
		return &storage.ZoneHuadongZheJiang2
	case 3:
		return &storage.ZoneHuabei
	case 4:
		return &storage.ZoneHuanan
	default:
		return &storage.ZoneHuadong
	}
}
